package com.istock.servicesample.config;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@ImportResource("classpath:spring-mvc.xml")
@ComponentScan("com.istock.servicesample.controller")
@EnableSwagger2
public class WebConfig extends WebMvcConfigurerAdapter {

	//如果使用jackson,请配置date的输出格式
	/*@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
		List<MediaType> mediaList = new ArrayList<MediaType>();
		mediaList.add(MediaType.APPLICATION_JSON);
		mediaList.add(MediaType.TEXT_HTML);
		mediaList.add(MediaType.TEXT_PLAIN);
		mediaList.add(new MediaType("application", "*+json"));
		converter.setSupportedMediaTypes(mediaList);
		FastJsonConfig jsonConfig = new FastJsonConfig();
		jsonConfig.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat);
		converters.add(converter);
	}*/
	
	@Bean
    public Validator Validator(){
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                // true开启快速校验，判断到有一个校验不通过就返回
                .failFast(false)
                .buildValidatorFactory();
        return validatorFactory.getValidator();
    }
	
	@Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.istock.servicesample.controller"))
                .paths(PathSelectors.any())
                .build();
    }
	
	private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("纯接口框架 RESTful APIs")
                .version("1.0")
                .build();
    }
}
